<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-tickets"></i> 章节作业管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-row justify="end" style="margin-bottom: 20px;">
                <el-col :span="6">
                    <el-input style="width:100%" v-model="select_word" placeholder="请输入APP名称或者id" class="handle-input mr10"></el-input>
                </el-col>
                <el-col :span="6">
                    <el-button style="margin-left: 10px;" type="primary" icon="search" @click="obtainStudent();cur_page = 1">搜索</el-button>
                </el-col>
            </el-row>
            <el-table :data="tableData" border ref="multipleTable" v-loading="loadingFlag">
                <!-- <el-table-column type="index" width="40"></el-table-column> -->
                <!-- sortable -->
                <el-table-column label="作业提交时间">
                    <template slot-scope="scope">
                        {{scope.row.create_time | formatTime}}
                    </template>
                </el-table-column>
                <el-table-column label="章节标题" prop="note_title"></el-table-column>
                <el-table-column label="APP用户ID" prop="user_id"></el-table-column>
                <el-table-column label="APP用户名称" prop="nickName"></el-table-column>
                <el-table-column label="批改状态">
                    <template slot-scope="scope">
                        {{scope.row.correct === 1 ? '已批改': ''}}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="small" type="success" :plain="true" v-if="scope.row.recommend" @click="setRecommendShow(scope.$index, scope.row)">取消推荐</el-button>
                        <el-button type="info" v-if="!scope.row.recommend" @click="setRecommendShow(scope.$index, scope.row)">精选推荐</el-button>
                        <el-button size="small" type="primary" @click="jobDetailsShow(scope.$index, scope.row)">查看编辑</el-button>
                        <el-button size="small" type="danger" @click="delStudentJobShow(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next, jumper" :total="total" :page-size="10">
                </el-pagination>
            </div>
        </div>

        <!-- 删除学员 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="delStudentJob()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 是否设置精选评论 删除提示框 -->
        <el-dialog title="提示" :visible.sync="recommendVisible" width="300px" center>
            <div class="del-dialog-cnt">{{saveData.recommend ? '确定取消该作业为精选作业？' : '确定取消该作业设置为精选作业？'}}</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="recommendVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRecommend()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="作业详情" :visible.sync="dialogFormVisible">
            <div class="job-details">
                <div class="table">
                    <div class="crumbs">
                        <el-breadcrumb separator="/">
                            <el-breadcrumb-item>
                                <i class="el-icon-tickets"></i> 作业详情</el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>
                    <div class="container" v-if="saveData">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <div class="meun-title">日期时间</div>
                                <div class="meun-item">{{saveData.create_time | formatTime}}</div>
                            </el-col>
                            <el-col :span="6">
                                <div class="meun-title">章节标题</div>
                                <div class="meun-item">{{saveData.note_title}}</div>
                            </el-col>
                            <el-col :span="5">
                                <div class="meun-title">APP用户ID</div>
                                <div class="meun-item">{{saveData.user_id}}</div>
                            </el-col>
                            <el-col :span="7">
                                <div class="meun-title">APP用户名称</div>
                                <div class="meun-item">{{saveData.nickName}}</div>
                            </el-col>
                        </el-row>
                        <div v-for="(job,jIndex) in saveData.content" :key="jIndex">
                            <!--学生作业视频-->
                            <el-card class="box-card distance-100" v-if="job.status === 1">
                                <div v-for="(affix,aIndex) in job.content" :key="aIndex">
                                    <h3 v-if="affix.status === 10 && affix.url">作业视频附件</h3>
                                    <!-- <div id="dplayer" style="max-width: 80%;margin: 0 auto" v-if="affix.status === 10">{{videoPlayer(affix.url,affix.content)}}</div> -->
                                    <video :src="affix.url" controls width="100%" height="100%"  v-if="affix.status === 10"></video>
                                </div>
                            </el-card>
                            <el-card class="box-card distance-100" v-if="job.status === 1">
                                <div v-for="(affix,aIndex) in job.content" :key="aIndex">
                                    <h3 v-if="affix.status === 10 && aIndex === 0">作业图片</h3>
                                    <img :src="affix.content" v-if="affix.status === 11" style="width: 80%;margin: 10px auto;display: block">
                                </div>
                            </el-card>
                            <el-card class="box-card distance-100" v-if="job.status === 2">
                                <h3>作业音频附件</h3>
                                <aplayer :music="{
                                    src: job.content,
                                    pic: 'https://moeplayer.b0.upaiyun.com/aplayer/secretbase.jpg'
                                }" />
                            </el-card>

                            <!--学生作业文字-->
                            <el-card class="box-card distance-100" v-if="job.status === 0">
                                <h3>作业内容</h3>
                                {{job.content}}
                            </el-card>
                        </div>

                    </div>
                    
                    <div class="container" style="margin-top: 15px;">
                        <h3>老师点评</h3>
                        <el-input type="textarea" :disabled="disabledWrite" :autosize="{ minRows: 4, maxRows: 6}" placeholder="请输入内容" v-model="saveData.teach">
                        </el-input>
                        <div style="text-align: center;margin-top: 15px;">
                            <el-button type="primary" @click="selectTeachShow()">点评发布</el-button>
                        </div>
                    </div>
                    <div class="container" style="margin-top: 15px;">
                        <el-alert v-if="saveData.super_user === 1" title="此作业为管理员的作业，选为精选作业请注意" type="error"></el-alert>
                        <div style="text-align: center;margin-top: 15px;">
                            <el-button type="success" plain v-if="saveData.recommend" @click="setRecommend();dialogFormVisible = false;">取消精选作业</el-button>
                            <el-button type="success" plain v-if="!saveData.recommend" @click="setRecommend();dialogFormVisible = false;">选为精选作业</el-button>
                        </div>
                    </div>

                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="getData()">返回</el-button>
            </div>
        </el-dialog>
        
        <el-dialog
            title="选择教师点评"
            :visible.sync="teachVisible"
            width="300px">
            <div>
                <el-select v-model="teachValue" placeholder="请选择">
                    <el-option
                        v-for="item in teachList"
                        :key="item.student_id"
                        :label="item.nickName"
                        :value="item.student_id">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="teachVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitJobComment()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// 视频插件
// import "DPlayer/dist/DPlayer.min.css";
// import DPlayer from "DPlayer";
// 音频插件
import Aplayer from "vue-aplayer";
import { dateRegExp } from "@/config/filter";
import {
    obtainJobList,
    delJobDetails,
    setJobRecommend,
    cancelJobRecommend,
    updateJobComment,
    obtainTeachList,
    obtainSearchJobList,
    // updateCorrect

    obtainChapterJob
} from "@/config/api";
export default {
    components: {
        Aplayer
    },
    data() {
        return {
            loadingFlag: false,
            tableData: [],
            cur_page: 1,
            idx: -1,
            // 作业详情 显示
            dialogFormVisible: false,
            textarea: "",
            // 删除作业 对话框 显示
            delVisible: false,
            // 是否设置为精选作业 对话框 显示
            recommendVisible: false,
            // 总条数
            total: 0,
            // 批次ID
            batch_id: "",
            // 保存被点击的数据
            saveData: {},

            // 视频播放中，禁止输入
            disabledWrite: false,
            // 视频播放器
            dp: null,
            // 选择教师点评
            teachVisible: false,
            // 教师列表
            teachList: [],
            // 选择了那个教师
            teachValue: '',
            // 搜索
            is_search: false,
            select_word: '',
        };
    },
    watch: {
        // 深度监听
        $route: {
            handler(item) {
                let self = this;
                console.log(item.query, ".........路由");
                if (JSON.stringify(item.query) != "[]") {
                }
            },
            deep: true
        }
    },
    filters: {
        formatTime(time) {
            return dateRegExp(time - 0, "yyyy-MM-dd hh:mm:ss");
        }
    },
    created() {
        this.getData();
    },
    methods: {
        fetchDate() {
            console.log("理由");
        },
        // 获取 easy-mock 的模拟数据
        async getData() {
            this.loadingFlag = true;
            // let data = await obtainJobList(
            //     this.cur_page,
            //     this.$route.query.batch_id
            // );
            let data = await obtainChapterJob(
                this.cur_page
            );
            
            console.log("数据", data);
            this.tableData = data.data;
            this.total = data.total;
            this.dialogFormVisible = false;
            if (this.pd != null ){
                this.pd.destroy()
            }
            this.loadingFlag = false;
        },
        // 删除学员 显示
        delStudentJobShow(index, row) {
            this.delVisible = true;
            this.saveData = row;
        },
        // 删除学员
        async delStudentJob() {
            this.delVisible = false;
            await delJobDetails(this.saveData.job_id)
                .then(res => {
                    console.log("删除学员:", res);
                    if (res.msg === "success") {
                        this.$message({
                            type: "success",
                            message: "删除成功!"
                        });
                    } else {
                        this.$message.error("删除失败" + str);
                    };
                    // 重新获取数据
                    this.obtainStudent();
                })
                .catch(err => {
                    console.error(err);
                });
        },
        // 设置为精选评论 显示
        setRecommendShow(index, row) {
            this.recommendVisible = true;
            this.saveData = row;
        },
        // 设置为精选评论
        async setRecommend() {
            this.recommendVisible = false;
            if (this.saveData.recommend) {
                await cancelJobRecommend(this.saveData.job_id)
                    .then(res => {
                        console.log("取消为精选评论:", res);
                        if (res.msg === "success") {
                            this.$set(this.saveData, "recommend", 1);
                            this.$message({
                                type: "success",
                                message: "取消成功!"
                            });
                        } else {
                            this.$message.error("失败" + str);
                        }
                        // 重新获取数据
                        this.obtainStudent();
                    })
                    .catch(err => {
                        console.error(err);
                    });
            } else {
                await setJobRecommend(this.saveData.job_id)
                    .then(res => {
                        console.log("设置为精选评论:", res);
                        if (res.msg === "success") {
                            this.$set(this.saveData, "recommend", 0);
                            this.$message({
                                type: "success",
                                message: "设置成功!"
                            });
                        } else {
                            this.$message.error("失败" + str);
                        }
                        // 重新获取数据
                        this.obtainStudent();
                    })
                    .catch(err => {
                        console.error(err);
                    });
            }
        },
        // 作业详情显示
        jobDetailsShow(index, row) {
            console.log("作业详情显示:", row);
            this.saveData = row;
            this.dialogFormVisible = true;
            this.saveData.content.comment =
                row.content && row.content.comment ? row.content.comment : "";
            // setTimeout(() => {
            //     this.videoPlayer(row.content.video)
            // }, 300);
        },
        // 获取此批次下的教师
        async selectTeachShow () {
            try {
                this.teachValue = '';
                let teach =  await obtainTeachList(this.$route.query.batch_id)
                this.teachVisible = true;
                this.teachList = teach.data;
            } catch (e) {
                console.error(e)
            }
        },
        // 提交老师点评
        async submitJobComment() {
            if (!this.saveData.teach) {
                this.$message.error('请输入点评内容');
                return false;
            };
            if (!this.teachValue) {
                this.$message.error('请选择教师');
                return false;
            }
            this.dialogFormVisible = false;
            this.teachVisible = false;
            await updateJobComment(this.saveData.job_id, this.saveData.teach,this.teachValue)
                .then(res => {
                    console.log("提交老师点评:", res);
                    if (res.msg === "success") {
                        // 重新获取数据
                        this.obtainStudent();
                        this.$message({
                            type: "success",
                            message: "点评成功!"
                        });
                    } else {
                        this.$message.error("失败");
                    }
                    this.obtainStudent();
                })
                .catch(err => {
                    console.error("失败:", err);
                    this.obtainStudent();
                });
        },
        // 视频渲染
        videoPlayer(url,pic) {
            // let self = this;
            // console.log("url");
            // setTimeout(() => {
            //     this.$nextTick(() => {
            //         this.dp = new DPlayer({
            //             container: document.getElementById("dplayer"),
            //             hotkey: false,
            //             preload: "none",
            //             video: {
            //                 url,
            //                 pic
            //             }
            //         });
            //         this.dp.on("play", async function() {
            //             self.$message({
            //                 type: "success",
            //                 message: "视频在播放期间不能输入点评"
            //             });
            //         });
            //         // 视频已经播放完了
            //         this.dp.on("playing", async function() {
            //             console.log("播放中");
            //             self.disabledWrite = true;
            //         });
            //         this.dp.on("pause", async function() {
            //             console.log("暂停");
            //             self.disabledWrite = true;
            //         });
            //         // 视频已经播放完了
            //         this.dp.on("ended", async function() {
            //             self.disabledWrite = false;
            //             // await updateCorrect(
            //             //     self.saveData.job_id,
            //             //     self.saveData.batch_id
            //             // )
            //             //     .then(res => {
            //             //         console.log("更新作业状态", res);
            //             //         self.disabledWrite = false;
            //             //         if (res.msg === "success") {
            //             //             self.$message({
            //             //                 type: "success",
            //             //                 message:
            //             //                     "视频已经播放完毕，此作业批改状态已更新!"
            //             //             });
            //             //         } else {
            //             //             self.$message.error("失败" + str);
            //             //         }
            //             //     })
            //             //     .catch(err => {
            //             //         console.error("失败", err);
            //             //     });
            //         });
            //     });
            // }, 500);
        },

        // 分页导航
        handleCurrentChange(val) {
            console.log(val)
            this.cur_page = val;
            this.obtainStudent();
        },
        // 获取列表
        async obtainStudent() {
            // 非搜索
            if (!this.select_word) {
                // this.cur_page = 1
                this.getData();
                this.is_search = false;
                return false;
            };
            // 搜索
            this.is_search = true;
            let name = this.select_word.replace(/(^\s*)|(\s*$)/g,"")
            await obtainChapterJob(this.cur_page,name)
                .then( res => { 
                    console.log('用户搜索',res)
                    if (res.status === 200) {
                        this.tableData = res.data;
                        this.total = res.total
                    } else {
                        this.$message.error("用户不存在");
                    }
                })
        },
        handleDelete(index, row) {
            this.idx = index;
            this.delVisible = true;
        },
        // 确定删除
        deleteRow() {
            this.tableData.splice(this.idx, 1);
            this.$message.success("删除成功");
            this.delVisible = false;
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt {
    font-size: 16px;
    text-align: center;
}
.meun-title,
.meun-item {
    display: block;
}
.meun-title {
    font-size: 14px;
}
.meun-item {
    margin-top: 5px;
    color: #3c3c3c;
    font-size: 12px;
}
</style>
